package SC12Project.Milestone1.Weather;

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

/**
 * Service provider for a Weather Information Database
 * 
 * @author Diego Havenstein
 */
public class WeatherProvider
    implements WeatherWS
{

    private File f;

    private Unmarshaller u;

    private WeatherList wl;

    /**
     * Constructor
     */
    public WeatherProvider()
    {
        parseAndInit( "../datasource/ds_2_6.xml" );
    }

    void parseAndInit( String path )
    {
        this.f = new File( path );

        try
        {
            ClassLoader cl = SC12Project.Milestone1.Weather.ObjectFactory.class.getClassLoader();
            String packageName = WeatherList.class.getPackage().getName();
            JAXBContext jc = JAXBContext.newInstance( packageName, cl );
            this.u = jc.createUnmarshaller();
            @SuppressWarnings( "unchecked" )
            JAXBElement<WeatherList> root = (JAXBElement<WeatherList>) u.unmarshal( f );
            this.wl = root.getValue();
            /*
             * JAXBContext context = JAXBContext.newInstance(WeatherList.class); this.u = context.createUnmarshaller();
             * this.m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
             * this.wl = (WeatherList) u.unmarshal(f);
             */
        }
        catch ( JAXBException e )
        {
            e.printStackTrace();
        }
    }

    @Override
    public WeatherInfo queryWeather( Date date, String location )
    {
        int n = wl.getWeather().size();
        for ( int i = 0; i < n; i++ )
            if ( wl.getWeather().get( i ).getLocation().equals( location )
                && date.getDate() == wl.getWeather().get( i ).getDate().getDate()
                && date.getMonth() == wl.getWeather().get( i ).getDate().getMonth()
                && date.getYear() == wl.getWeather().get( i ).getDate().getYear() )
            {
                return wl.getWeather().get( i );
            }
        return new WeatherInfo();
    }

}
